use rusqlite::Connection;

use crate::{ADDRS, GLOBAL_CONFIG};

#[tauri::command]
pub fn del_addr(id: i64) -> String {
    println!("db deleting...");
    let conn = Connection::open(GLOBAL_CONFIG.lock().unwrap().address.db_file.clone()).unwrap();
    conn.execute("DELETE FROM address WHERE id = ?1", [id]).expect("删除失败");
    conn.execute("DELETE FROM addr_label WHERE addr_id = ?1", [id]).expect("删除失败");
    // 删除不再使用的tag
    conn.execute("
        DELETE FROM label 
        WHERE id IN (
        SELECT id FROM label l 
        LEFT JOIN addr_label al ON l.id = al.label_id 
        WHERE al.label_id IS NULL )
    ", []).expect("删除失败");
    ADDRS.lock().unwrap().remove(&id);
    "删除成功".to_string()
}
